<?php
/**
 * Created by PhpStorm.
 * User: dengpan
 * Date: 2017/1/9
 * Time: 21:54
 */

$serv = new Swoole\Websocket\Server("127.0.0.1", 8002);


$cookie_file = "/tmp/ws_user_cookies";
if(file_exists($cookie_file)) {
    unlink($cookie_file);
}
$serv->on('Open', function($server, $req) {
    //连接建立的时候,cookie,fd 每行记录下来
    global $cookie_file;
    $f = file_put_contents($cookie_file, $req->header['sec-websocket-key']. "," . $req->fd . "\n", FILE_APPEND);
    echo "connection open: ".$req->fd . "\n";


    $user_msg_file = "/tmp/user_" . $req->fd;
    if(file_exists($user_msg_file)) {
        unlink($user_msg_file);
    }
});

$serv->on('Message', function($server, $frame) {
    echo "message: ".$frame->data;
    $data = "已接收: " . $frame->data . "    " . date("Y-m-d H:i:s");

    $user_msg_file = "/tmp/user_" . $frame->fd;
    file_put_contents($user_msg_file, $frame->data, FILE_APPEND);
    global $cookie_file;


    //如果是发送所有的消息, 给所有人推送消息
    if(mb_strstr($frame->data, "发送所有") != false) {
        //给所有人推送消息
        $f = fopen($cookie_file, "r+");
        $allFd = [];
        while (!feof($f)) {
            $line = trim(fgets($f));
            if(!empty($line)) {
                $a = explode(",", $line);
                if(count($a) == 2) {
                    //把文件描述符添加进去
                    $allFd[] = $a[1];
                }
            }
        }
        fclose($f);
        foreach ($allFd as $fd) {
            $server->push($fd, "用户fd=". $frame->fd. "  ". mb_substr($frame->data, 5));
        }
    } elseif (mb_strstr($frame->data, "我的所有") != false) {
        $server->push($frame->fd, file_get_contents("/tmp/user_" . $frame->fd));
    }
    else {
        $server->push($frame->fd, $data);
    }
});

$serv->on('Close', function($server, $fd) {
    echo "connection close: ".$fd;

    //删除所有用户文件里面的该行记录
    global $cookie_file;
    $f = fopen($cookie_file, "r");
    $strArr = [];
    while (!feof($f)) {
        $line = trim(fgets($f));
        if(!empty($line)) {
            $a = explode(",", $line);
            if(count($a) == 2) {
                if($a[1] != $fd) {
                    $strArr[] = $line;
                }
            }
        }
    }
    fclose($f);
    $f = fopen($cookie_file, "w");
    foreach ($strArr as $line) {
        fwrite($f, $line . "\n");
    }
    fclose($f);

    //删除用户message文件
    $user_file = "/tmp/user_" . $fd;
    if(file_exists($user_file)) {
        unlink($user_file);
    }

});

$serv->start();